package com.example.administrator.zhongyichou.net.core;

import com.example.administrator.zhongyichou.help.UrlReplace;
import com.example.administrator.zhongyichou.net.presentor.UploadFileAPI;
import com.example.administrator.zhongyichou.net.protocol.GsonBaseProtocol;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;

/**
 * Created by lichenyu on 2017/9/30.
 * 文件上传的httploader
 */

public class UploadHttpLoader extends HttpLoader {

    private List<File> paths;//file别表
    private Map<String, String> map;//参数
    private String url;
    private String imgKey="info_img";

    /**
     * 构造传递监听的接口，以及需要被解析的字节码文件
     *
     * @param parseClass
     */
    public UploadHttpLoader(Class<? extends GsonBaseProtocol> parseClass) {
        super(parseClass);
    }

    public void setParams(String url, List<File> paths, Map<String, String> map) {
        this.paths = paths;
        setResponseUrl(UrlReplace.replace(url));
        map.put("cmd", url);
        this.map = map;
    }

    public void setParams(String url, List<File> paths, Map<String, String> map,String imgKey) {
        this.paths = paths;
        setResponseUrl(UrlReplace.replace(url));
        map.put("cmd", url);
        this.map = map;
        this.imgKey=imgKey;
    }

    @Override
    public Observable<ResponseBody> structureObservable(Retrofit mRetrofit) {
        UploadFileAPI uploadFileAPI = mRetrofit.create(UploadFileAPI.class);
        //创建file的RequestBody
        Map<String, RequestBody> photos = new HashMap<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            photos.put(entry.getKey(), RequestBody.create(MediaType.parse("text/plain"), entry.getValue()));
        }
        if (paths.size() > 0) {
            for (int i = 0; i < paths.size(); i++) {
                photos.put(imgKey + i + "\";filename=\"" + paths.get(i).getName(), RequestBody.create(MediaType.parse("image/*"), paths.get(i)));
            }
        }
        Observable<ResponseBody> responseBodyObservable = uploadFileAPI.upload(photos);
        return responseBodyObservable;
    }
}
